package org.jupiter.blog.service.service.impl;

import org.jupiter.blog.api.convertor.JupiterConfigConvertor;
import org.jupiter.blog.api.domain.JupiterConfig;
import org.jupiter.blog.api.dto.JupiterConfigDTO;
import org.jupiter.blog.service.mapper.JupiterConfigMapper;
import org.jupiter.blog.service.service.JupiterConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class JupiterConfigServiceImpl implements JupiterConfigService {

	@Autowired
	private JupiterConfigMapper configMapper;

	@Autowired
	private JupiterConfigConvertor configConvertor;

	@Override
	@Transactional
	public void createConfig(JupiterConfigDTO dto) {
		JupiterConfig config = configConvertor.toEntity(dto);
		if (!StringUtils.hasText(config.getUuid())){
			config.setUuid(UUID.randomUUID().toString());
		}
		config.setCreateTime(LocalDateTime.now());
		config.setUpdateTime(LocalDateTime.now());
		configMapper.insert(config);
	}

	@Override
	@Transactional(readOnly = true)
	public JupiterConfigDTO getById(String uuid) {
		JupiterConfig config = configMapper.selectByUuid(uuid);
		return configConvertor.toDto(config);
	}

	@Override
	@Transactional
	public void updateConfig(String uuid, JupiterConfigDTO dto) {
		JupiterConfig config = configConvertor.toEntity(dto);
		config.setUuid(uuid);
		config.setUpdateTime(LocalDateTime.now());
		configMapper.updateByUuidSelective(config);
	}

	@Override
	@Transactional
	public void deleteConfig(String uuid) {
		configMapper.deleteByUuid(uuid);
	}

	@Override
	@Transactional(readOnly = true)
	public List<JupiterConfigDTO> getByPage(JupiterConfigDTO queryDTO) {
		int offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
		List<JupiterConfig> configs = configMapper.selectByPage(
				queryDTO.getConfigName(),
				offset,
				queryDTO.getSize()
		);
		return configConvertor.toDtoList(configs);
	}

	@Override
	@Transactional(readOnly = true)
	public long getCount(JupiterConfigDTO queryDTO) {
		return configMapper.countByQuery(queryDTO.getConfigName());
	}

	@Override
	@Transactional(readOnly = true)
	public JupiterConfigDTO getByName(String configName) {
		JupiterConfig config = configMapper.selectByConfigName(configName);
		return configConvertor.toDto(config);
	}

	@Override
	@Transactional
	public void refreshCache() {
		// 这里可以实现具体的缓存刷新逻辑
		// 比如清除Redis缓存，重新加载配置等
		System.out.println("配置缓存已刷新");
	}

	@Override
	@Transactional
	public void insertBatch(List<JupiterConfigDTO> dtoList) {
		for (JupiterConfigDTO dto : dtoList){
			createConfig(dto);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public boolean existsByName(String configName) {
		return configMapper.countByConfigName(configName) > 0;
	}
}
